package com.woniuxy.util;

import com.woniuxy.entity.dto.YiDTO;
import com.woniuxy.util.ResponseData;
import com.woniuxy.util.ResponseEnum;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.function.Function;

/**
 * @program: tsm
 * @description:
 * 导入功能，根据POI依赖写入，暂时抛弃使用
 * @create: 2024-10-21 10:09
 **/
@Service
public class ImportService {

    public <T> ResponseData<List<T>> importExcelData(MultipartFile file, Map<String, Integer> fieldMapper, Function<Row, T> rowMapper) {
        List<T> resultList = new ArrayList<>();
        try {
            // 处理上传的文件
            InputStream inputStream = file.getInputStream();
            Workbook workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);

            // 解析 Excel 文件中的数据行
            for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                Row dataRow = sheet.getRow(rowIndex);

                // 通过自定义的 rowMapper 解析每一行数据
                T parsedData = rowMapper.apply(dataRow);
                resultList.add(parsedData);
            }

            workbook.close();
            inputStream.close();

            // 假设需要将解析的数据保存到数据库
            if (!resultList.isEmpty()) {
//                Data.saveAll(resultList);  // 将解析后的数据保存到数据库,将来有机会再实现
            }
            // 返回成功的结果
            return new ResponseData<List<T>>().ok(resultList);

        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseData<List<T>>().fail(ResponseEnum.NOT_FILE);
        }
    }
}
